import 'package:carousel_slider/carousel_slider.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:development_assistant/controller/test_controller.dart';
import 'package:development_assistant/ui/screen/widget/home_background.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../config/colors.dart';
import '../../../config/font.dart';
import '../../../config/image_config.dart';
import '../../../model/ChartData.dart';
import '../widget/custom_text.dart';
import '../widget/frosted_glass.dart';
class TestAssistant extends StatelessWidget {

  final TestController testController=Get.put(TestController());

  TestAssistant({super.key});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: testController.getTestList(),
      builder: (context,snapshot) {
        return HomeBackground(
            front: SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: 50.h,horizontal: 20.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _testList(),
                      Text("测试详情".tr,style: FontConfig.titleStyle,),
                      SizedBox(height: 10.h,),
                      _testReport(),
                    ],
                  ),
                )
            )
        );
      }
    );
  }


  _testList(){
    envDesc(String envType){
      return Row(
        children: [
          FrostedGlass(
              width: 20.h,
              height: 20.h,
              color: Colors.white12,
              borderRadius:BorderRadius.circular(50),
              sigmaX: 10, sigmaY:10,
              child: Text(
                envType[0],
                style:TextStyle(color: ColorsConfig.envTagColors[envType],fontWeight: FontWeight.bold,fontSize: 15.sp),)
          ),
          SizedBox(width: 5.w,),
          Text(envType,style: const TextStyle(fontWeight: FontWeight.bold),)
        ],
      );
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("自动化测试".tr,style: FontConfig.titleStyle,),
            SizedBox(
              child: ElevatedButton.icon(
                onPressed: (){
                  Get.toNamed("/AutoTest");
                },
                icon: const Icon(Icons.dataset_linked_outlined),
                label: Text("测试".tr),
                style: ElevatedButton.styleFrom(
                    backgroundColor:  ColorsConfig().buttonColorOfTheme,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)
                    )
                ),
              ),
            ),
          ],
        ),
        Obx(() => testController.testList.isEmpty?_testFigure():SizedBox(
          height: 160.h,
          child: CarouselSlider(
            options: CarouselOptions(
                height: 400.0,
                aspectRatio: 16/9,
                initialPage: 0,
                enlargeCenterPage: true,
                onPageChanged: (index,reason){
                  testController.pickIndex.value=index;
                }
            ),
            items: List<Widget>.generate(testController.testList.length, (index) {
              return Container(
                  width: 400.w,
                  margin: EdgeInsets.symmetric(vertical: 10.h),
                  padding: EdgeInsets.symmetric(vertical: 10.h,horizontal: 20.w),
                  decoration: BoxDecoration(
                      gradient: ColorsConfig().cardColorOfTheme,
                      borderRadius: BorderRadius.circular(20)
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          CustomText(text: "${testController.testList[index]["test_name"]}", textStyle: FontConfig.databaseNameStyle),
                          IconButton(
                            splashColor: Colors.transparent,
                            highlightColor: Colors.transparent,
                            onPressed: (){
                              Get.toNamed("/TestDetail",arguments: [index]);
                            },
                            icon: const Icon(Icons.more_horiz),
                          ),
                        ],
                      ),
                      envDesc(testController.testList[index]["test_env"].toString().tr),
                      CustomText(text: "${'测试间隔停顿'.tr} : ${testController.testList[index]["test_interval"]} ms", textStyle:FontConfig.databaseInformationStyle),
                      CustomText(text: "${'测试线程'.tr} : ${testController.testList[index]["test_thread"]} ", textStyle:FontConfig.databaseInformationStyle),
                      CustomText(text: "${'测试时间'.tr} : ${testController.testList[index]["test_date"]}", textStyle:FontConfig.databaseInformationStyle),
                    ],
                  )
              );
            }),
          ),
        ),)
      ],
    );
  }

  _methodTag(String requestMethod){
    return SizedBox(
      width: 50.w,
      height: 30.h,
      child: TextButton(
          style: TextButton.styleFrom(
              foregroundColor: Colors.white,
              backgroundColor: ColorsConfig.methodTagColors[requestMethod],
              shape:RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)
              )
          ),
          onPressed: (){
          },
          child: Text(requestMethod)
      ),
    );
  }

  _charts(){
    var seriesList = [
      charts.Series(
        id: 'Pie',
        domainFn: (ChartData data, _) => data.pieLabel,
        measureFn: (ChartData data, _) => data.pieValue,
        data: [
          ChartData('success', testController.testList[testController.pickIndex.value]["test_success"]),
          ChartData('error', testController.testList[testController.pickIndex.value]["test_error"]),
        ],
      ),
    ];
    return SizedBox(
        width: 130.w,
        height: 130.w,
        child: charts.PieChart(
            seriesList,
            animate: true,
        )
    );
  }

  _testData(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              width: 10.w,
              height: 10.w,
              margin: EdgeInsets.symmetric(horizontal: 10.w),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(50),
                  color: Colors.green
              ),
            ),
            Text("${'成功次数'.tr} : ${testController.testList[testController.pickIndex.value]["test_success"]} ",style: FontConfig.fieldTitle,),
          ],
        ),
        Row(
          children: [
            Container(
              width: 10.w,
              height: 10.w,
              margin: EdgeInsets.symmetric(horizontal: 10.w),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(50),
                  color: Colors.green
              ),
            ),
            Text("${'成功次数'.tr} : ${testController.testList[testController.pickIndex.value]["test_error"]} ",style: FontConfig.fieldTitle,),
          ],
        )
      ],
    );
  }

  _testReport(){
    List<Widget> tabs=[
      Container(
        width: 100.w,
        height: 30.h,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: ColorsConfig().buttonColorOfTheme
        ),
        child: Center(child: Text("测试步骤".tr,style: TextStyle(fontWeight: FontWeight.bold),)),
      ),
      Container(
        width: 100.w,
        height: 30.h,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: ColorsConfig().buttonColorOfTheme
        ),
        child: Center(child: Text("测试报告".tr,style: TextStyle(fontWeight: FontWeight.bold))),
      ),
    ];
    List<Widget> tabsView=[
      Obx(() => ListView(
        children: List<Widget>.generate(testController.testApiList[testController.pickIndex.value].length, (index) {
          return Container(
              width: 300.w,
              height: 70.h,
              margin: EdgeInsets.symmetric(vertical: 10.h),
              padding: EdgeInsets.symmetric(vertical: 10.h,horizontal: 20.w),
              decoration: BoxDecoration(
                  gradient: ColorsConfig().cardColorOfTheme,
                  borderRadius: BorderRadius.circular(20)
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      CustomText(text: testController.testApiList[testController.pickIndex.value][index]["api_name"], textStyle: FontConfig.apiName),
                      _methodTag(testController.testApiList[testController.pickIndex.value][index]["api_method"]),
                    ],
                  ),
                  CustomText(text: testController.testApiList[testController.pickIndex.value][index]["api_url"], textStyle:  FontConfig.urlStyle),
                ],
              )
          );
        }),
      )),
      Obx(() => Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15),
            border: Border.all(color:Colors.grey,width: 1)
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                _charts(),
                _testData(),
              ],
            ),
            CustomText(text: "${'测试间隔停顿'.tr} : ${testController.testList[testController.pickIndex.value]["test_interval"]} ms", textStyle:TextStyle(fontWeight: FontWeight.bold,fontSize: 15.sp)),
            SizedBox(height: 3.h,),
            CustomText(text: "${'测试线程'.tr} : ${testController.testList[testController.pickIndex.value]["test_thread"]} ", textStyle:TextStyle(fontWeight: FontWeight.bold,fontSize: 15.sp)),
            SizedBox(height: 3.h,),
            CustomText(text: "${'测试时间'.tr} : ${testController.testList[testController.pickIndex.value]["test_date"]}", textStyle:TextStyle(fontWeight: FontWeight.bold,fontSize: 15.sp)),
            SizedBox(height: 3.h,),
            CustomText(text: "${'循环次数'.tr} : ${testController.testList[testController.pickIndex.value]["test_cycles"]} ", textStyle: TextStyle(fontWeight: FontWeight.bold,fontSize: 15.sp)),
            SizedBox(height: 3.h,),
            CustomText(text: "${'测试总耗时'.tr} : ${testController.testList[testController.pickIndex.value]["request_time"]} ms", textStyle: TextStyle(fontWeight: FontWeight.bold,fontSize: 15.sp)),
            SizedBox(height: 3.h,),
            CustomText(text: "${'平均接口请求耗时'.tr} : ${testController.testList[testController.pickIndex.value]["average_time"]} ms", textStyle: TextStyle(fontWeight: FontWeight.bold,fontSize: 15.sp)),
          ],
        ),
      ))
    ];
    return SizedBox(
      height: 330.h,
      child: DefaultTabController(
        length: tabs.length,
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Colors.transparent,
          appBar: TabBar(
            indicator: const UnderlineTabIndicator(
              borderSide: BorderSide.none
            ),
            dividerColor: Colors.transparent,
            overlayColor: MaterialStateProperty.all<Color>(Colors.transparent),
            labelColor: Colors.white,
            tabs: tabs,
            padding: EdgeInsets.only(bottom: 10.h),
          ),
          body: Obx(()=>TabBarView(
            children: testController.testList.isEmpty?[_resultFigure(),_resultFigure()]:tabsView,
          )),
        ),
      ),
    );
  }

  _testFigure(){
    return Container(
      height: 160.h,
      margin: EdgeInsets.symmetric(vertical: 10.h),
      padding: EdgeInsets.symmetric(horizontal: 5.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15),
          gradient: ColorsConfig().figureOfTheme
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            ImageConfig.figureImage['test']!,
            width: 160.w,
          ),
          Container(
            width: 150.w,
            padding: EdgeInsets.symmetric(vertical: 40.h),
            child: Column(
              children: [
                Text("接口自动化测试".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 15.sp),),
                SizedBox(height: 5.h,),
                Text("模拟真实使用环境测试接口".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 10.sp),),
              ],
            ),
          )
        ],
      ),
    );
  }

  _resultFigure(){
    return Container(
      height: 150.h,
      width: 320.w,
      margin: EdgeInsets.symmetric(vertical: 10.h),
      padding: EdgeInsets.symmetric(vertical: 15.h),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15),
          gradient: ColorsConfig().figureOfTheme
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("自动化测试分析".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 15.sp),),
          SizedBox(height: 5.h,),
          Text("了解接口自动化测试的结果".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 10.sp),),
          Text("更好对接口和测试流程进行调整".tr,style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 10.sp),),
          Image.asset(
            ImageConfig.figureImage['result']!,
            width:180.w,
          ),
        ],
      ),
    );
  }

}

